<?php

/**
 * 菜单管理
 * @author Kevin_ren  <330202207@qq.com>
 */


namespace Admin\Controller;

use Common\Controller\BaseManageController;

class MenuController extends BaseManageController
{

    /**
     * 列表前置操作
     * @author Kevin_ren  <330202207@qq.com>
     */
    public function _before_index()
    {
        $menu = D('Menu')->getAllData();
        $this->assign('datas', $menu);
    }


    /**
     * 添加菜单
     * @author Kevin_ren  <330202207@qq.com>
     */
    public function _before_add()
    {
        $this->_before_index();
        $id    = I('parent_id');
        $menu['parent_id'] =  (int) $id;
        $this->assign('menu', $menu);
    }

    /**
     * 添加子菜单
     * @author Kevin_ren  <330202207@qq.com>
     */
    public function action()
    {
        $this->_before_index();
        $parent_id = I("parent_id");
        $this->assign('parent_id', $parent_id);
        $this->display();
    }

    public function action_save()
    {
        $menu = D('Menu')->saveAction();
        if ($menu !== false) {
            $this->simpleSuccess("保存成功", U("index"));
        } else {
            $this->simpleError(D('Menu')->getError());
        }
    }

    /**
     * 编辑菜单
     * @author Kevin_ren  <330202207@qq.com>
     */
    public function _before_edit()
    {
        $this->_before_index();
        $menu_id = I('id');
        $menu = D("Menu")->findMenu($menu_id);
        $menu['parent_id'] = $menu['parent_id'];
        $this->assign('menu', $menu);
    }

    /**
     * 删除菜单前置
     * @author Kevin_ren  <330202207@qq.com>
     */
    public function _before_delete()
    {
        $id   = I('id');
        $obj  = D('Menu');
        $menu = $obj->fetchAll();
        foreach ($menu as $val) {
            if ($val['parent_id'] == $id) {
                $this->simpleError('请先删除该菜单下子菜单');
            }
        }
    }

    /**
     * 更新菜单
     * @author Kevin_ren  <330202207@qq.com>
     */
    public function update()
    {
        $orderby = I('post.orderby', false);
        $obj = D('Menu');
        foreach ($orderby as $key => $val) {
            $data = array(
                'menu_id' => (int) $key,
                'orderby' => (int) $val
            );
            $obj->save($data);
        }
        $obj->cleanCache();
        $this->simpleSuccess('更新成功', U('index'));
    }
}